from . import admin_blu
from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info.models import User
from info.response_code import RET
from utils.common import user_login_data


# URL：/login
# 请求方式：POST
# 请求参数：name,password
#
@admin_blu.route('/login',methods = ['GET','POST'])
def admin_login():
    """登陆"""
    # GET请求
    if request.method == 'GET':
        return render_template('admin/login.html')

    # POST请求
    #   获取参数
    username = request.form.get('username')
    password = request.form.get('password')

    #   校验参数
    if not all([username, password]):
        return render_template('admin/login.html', errmsg = "参数输入不全")

    #   查询用户是否为管理员
    try:
        user = User.query.filter(User.nick_name == username, User.is_admin == True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/login.html', errmsg = "查询数据库失败")

    #   用户名和密码
    if not user or not user.check_passowrd(password):
        return render_template('admin/login.html', errmsg = "用户名或密码错误")

    # 储存session信息
    session['nick_name'] = username
    session['mobile'] = username
    session['user_id'] = user.id
    session['is_admin'] = user.is_admin

    # 返回数据
    return redirect(url_for('admin.index'))